package base.thread_JUC2.chapter04.demo03;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class TestCase {
    public static void main(String[] args) throws InterruptedException {
        //封装call()方法结果
        List<Future<Integer>> resultList=new ArrayList<>();
        // 创建固定大小的线程池
        ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int num = random.nextInt(10);
            System.out.println("计算"+num+"的阶乘");

            // 将阶乘任务丢进线程池，由线程池负责执行任务
            FactorialCalculator calculator = new FactorialCalculator(num);
            // TODO 是否发送任务后就不必等待任务结果，而是异步用Future接收结果
            Future<Integer> future = pool.submit(calculator);
            resultList.add(future);
        }

        // 等待所有任务执行完毕才打印所有任务的结果
        do {
            Thread.sleep(50);
        }while (pool.getCompletedTaskCount()<resultList.size());

        // 输出所有任务结果，future.get()方法会一直等待任务结束拿到结果
        for (int i=0; i< resultList.size(); i++) {
            Future<Integer> future = resultList.get(i);
            try {
                Integer result = future.get();// 获取call()方法的执行结果，否则一直等待call()方法的结果
                System.out.println("任务"+i+"执行结果："+result);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }

        pool.shutdown();
    }
}
